/**
 * 
 */
package info.niwota.webagent;

import info.niwota.webagent.peer.ChannelManager;

import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.xmpp.JID;
import com.google.appengine.api.xmpp.Message;
import com.google.appengine.api.xmpp.XMPPService;
import com.google.appengine.api.xmpp.XMPPServiceFactory;

/**
 * @author qiangli
 * 
 */
@SuppressWarnings("serial")
public class XMPPAgentServlet extends HttpServlet {

	private static final Logger log = Logger.getLogger(XMPPAgentServlet.class
			.getName());
	
	private static final XMPPService xmpp = XMPPServiceFactory.getXMPPService();
	private static final ChannelManager manager = ChannelManager.getInstance();
	
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		try {
			Message msg = xmpp.parseMessage(req);
			JID peer = msg.getFromJid();
			String body = msg.getBody();
			
			log.finest(peer + ": " + body);
			
			manager.dispatch(peer.getId().split("/")[0], body);
		} catch (Exception e) {
			log.log(Level.SEVERE, e.getMessage());
		}

	}

}
